package com.sys.web.back.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sys.common.pojo.ApiResponse;
import com.sys.common.pojo.ApiResponseEnum;
import com.sys.common.servlet.BaseServlet;
import com.sys.common.util.ConstatFinalUtil;
import com.sys.common.util.PageInfoUtil;
import com.sys.users.pojo.AAdmins;
import com.sys.users.service.IUsersDbService;
import com.sys.users.service.impl.UsersDbServiceImpl;

/**
 * 管理员首页操作
 * @author 陈岩
 */
@WebServlet(urlPatterns = "/back/AdminsBackServlet")
public class AdminsBackServlet extends BaseServlet
{
	private IUsersDbService usersDbService;
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		this.usersDbService = new UsersDbServiceImpl();
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 接收参数 */
		String method = request.getParameter("method");
		if ("main".equalsIgnoreCase(method))
		{
			/* 登陆后首页 */
			main(request, response);
		} else if ("welcome".equalsIgnoreCase(method))
		{
			/* 欢迎页面 */
			welcome(request, response);
		} else if ("logout".equalsIgnoreCase(method))
		{
			/* 退出 */
			logout(request, response);
		} else if ("adminsList".equalsIgnoreCase(method))
		{
			/* 管理员列表 */
			adminsList(request, response);
		} else if ("adminsInsert".equalsIgnoreCase(method))
		{
			/* 管理员添加 */
			adminsInsert(request, response);
		} else if ("adminsInsertSubmit".equalsIgnoreCase(method))
		{
			/* 管理员添加提交 */
			adminsInsertSubmit(request, response);
		}else if ("adminsUpdate".equalsIgnoreCase(method))
		{
			/* 管理员添加 */
			adminsUpdate(request, response);
		} else if ("adminsUpdateSubmit".equalsIgnoreCase(method))
		{
			/* 管理员添加提交 */
			adminsUpdateSubmit(request, response);
		}
	}

	/**
	 * 首页
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void main(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		String path = this.prefix + "/back/admins/main" + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 欢迎页面
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void welcome(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--welcome--");
		String path = this.prefix + "/back/admins/welcome" + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 退出页面
	 * 
	 * @return
	 * @throws IOException 
	 */
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--logout--");
		HttpSession session = request.getSession() ;
		String returnUrl = request.getParameter("returnUrl");
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 获取用户 */
		AAdmins admins = (AAdmins) this.findObjfromSession(request, "admins");
		if (returnUrl == null)
		{
			returnUrl = "";
		}
		try
		{
			/* 做一些清除的操作 */
			session.removeAttribute("admins");
			session.removeAttribute("urlList");
			session.removeAttribute("ipNow");
			returnUrl = URLEncoder.encode(returnUrl, "UTF-8");
			apiResponse.setCode(ApiResponseEnum.INFO_LOGOUT.getStatus());
		} catch (Exception e)
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 提示信息 */
		session.setAttribute("response", apiResponse.toJSON());
		/* 客户端跳转到登陆页面 */
		response.sendRedirect(request.getContextPath() + "/login.htm?returnUrl=" + returnUrl);

	}

	// ===管理员操作开始===
	/**
	 * 管理员列表页面
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void adminsList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/*
		 * 查询数据库 所有的数据以JSON的形式返回
		 */
		ApiResponse<AAdmins> apiResponse = this.usersDbService.findCondListAdminsService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		request.setAttribute("response", apiResponse.toJSON());
		String path = this.prefix + "/back/admins/adminsList" + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 打开添加管理员页面
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void adminsInsert(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminInsert--");
		Map<String, Object> condMap = new HashMap<String, Object>();
		String path = this.prefix + "/back/admins/adminsInsert" + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 添加管理员提交操作
	 * 
	 * @return
	 */
	public void adminsInsertSubmit(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsInsertSubmit--");
		/* 为对象赋值 */
		AAdmins admins = new AAdmins();
		/* 接收参数 */
		
		/* 保存结果 */
		ApiResponse dbResponse = this.usersDbService.saveOneAdminsService(admins);
		ConstatFinalUtil.SYS_LOGGER.info("--用户添加返回结果:{}--", dbResponse.toJSON());
		String result =  dbResponse.toJSON().toJSONString();
		this.printOut(result, response);
	}

	/**
	 * 打开更新管理员页面
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void adminsUpdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		// operType=update&idType=session
		ConstatFinalUtil.SYS_LOGGER.info("--adminsUpdate--");
		String id = request.getParameter("id");
		String operType = request.getParameter("operType");
		String idType = request.getParameter("idType");
		if (idType == null)
		{
			idType = "";
		}
		if (!"".equalsIgnoreCase(idType))
		{
			AAdmins adminsSess = (AAdmins) this.findObjfromSession(request, "admins");
			id = adminsSess.getId() + "";
		}
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AAdmins> apiResponse = this.usersDbService.findOneAdminsService(condMap);
		/* 存储request */
		request.setAttribute("response", apiResponse.toJSON());
		
		String path = "/back/admins/adminsInfo" ; 
		if ("update".equalsIgnoreCase(operType))
		{
			path = "/back/admins/adminsUpdate";
		} else if ("updatePass".equalsIgnoreCase(operType))
		{
			/* 更新密码 */
			path = "/back/admins/adminsUpdatePass";
		} else if ("resetPass".equalsIgnoreCase(operType))
		{
			/* 重置密码 */
			path = "/back/admins/adminsResetPass";
		}
		path = this.prefix + path + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 更新管理员提交操作
	 * 
	 * @return
	 */
	public void adminsUpdateSubmit(HttpServletRequest request,HttpServletResponse response)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsUpdateSubmit--");
		/* 数据库操作 */
		HttpSession session = request.getSession();
		ApiResponse dbResponse = new ApiResponse<>();
		String id = request.getParameter("id");
		String operType = request.getParameter("operType");

		String idType = request.getParameter("idType");
		if (idType == null)
		{
			idType = "";
		}
		if (!"".equalsIgnoreCase(idType))
		{
			AAdmins adminsSess = (AAdmins) this.findObjfromSession(request, "admins");
			id = adminsSess.getId() + "";
		}

		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AAdmins> apiResponse = this.usersDbService.findOneAdminsService(condMap);
		/* 获取java对象 */
		AAdmins admins = apiResponse.getDataOneJava();
		boolean flag = false;
		if ("update".equalsIgnoreCase(operType))
		{
			/* 接收参数 */
			String email = request.getParameter("email");
			String name = request.getParameter("name");
			String phone = request.getParameter("phone");
			String sex = request.getParameter("sex");
			String content = request.getParameter("content");
			String status = request.getParameter("status");
			admins.setName(name);
			admins.setEmail(email);
			admins.setPhone(phone);
			admins.setSex(Byte.valueOf(sex));
			admins.setContent(content);
			admins.setStatus(Byte.valueOf(status));
			flag = true;
		} else if ("updatePass".equalsIgnoreCase(operType))
		{
			/* 更新密码 */
			String password = request.getParameter("password");
			String souPass = request.getParameter("souPass");
			if (this.encryptUtil.checkStr(souPass, admins.getPassword()))
			{
				/* 原密码正确 */
				admins.setPassword(this.encryptUtil.encodeStr(password));
				flag = true;
			} else
			{
				/* 原密码不正确 */
				dbResponse.setCode(ApiResponseEnum.INFO_SOUPASS_INCORRECT.getStatus());
			}
		} else if ("resetPass".equalsIgnoreCase(operType))
		{
			String password = request.getParameter("password");
			/* 重置密码 */
			admins.setPassword(this.encryptUtil.encodeStr(password));
			flag = true;
		}
		dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + ""), Collections.EMPTY_MAP);
		if (flag)
		{
			dbResponse = usersDbService.updateOneAdminsService(admins);
		}
		ConstatFinalUtil.SYS_LOGGER.info("--用户更新返回结果:{}--", dbResponse.toJSON());
		String result =  dbResponse.toJSON().toJSONString();
		this.printOut(result, response);
	}
}